package com.lfy.pay.core;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.lfy.pay.domain.ScanCodeResponse;
import com.lfy.pay.zfb.AlipayApi;
import lombok.extern.slf4j.Slf4j;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 支付宝支付工具类
 *
 * @author <a href="https://www.lvfeiy.top">lvfeiyang</a>
 * @date 2024/8/10 20:35
 */
@Slf4j
public class AlipayUtil {
    /**
     * 扫码支付
     * @param model 支付参数
     * @return 扫码支付返回结果
     */
    public static ScanCodeResponse scanCodePay(AlipayTradePrecreateModel model) throws Exception {
        AlipayTradePrecreateResponse alipayTradePrecreateResponse = null;
        try {
            log.info("支付宝扫码支付入参：{}", JSONUtil.toJsonStr(model));
             alipayTradePrecreateResponse = AlipayApi.imageCreatePayToResponse(model);
            if (alipayTradePrecreateResponse.isSuccess()) {

                String code = alipayTradePrecreateResponse.getQrCode();
                BufferedImage image = QrCodeUtil.generate(code, 300, 300);
                // 将二维码图片转换成Base64编码的字符串
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImgUtil.writePng(image, outputStream);
                String base64 = Base64.encode(outputStream.toByteArray());
                return new ScanCodeResponse(base64, code);
            }
        } catch (AlipayApiException e) {
            log.error("扫码支付Api调用异常", e);
            throw e;
        }

        throw new RuntimeException("扫码支付失败,说明："+alipayTradePrecreateResponse.getSubMsg());
    }
    /* public static String generateQrCode(String content, int width, int height) {
     // 生成二维码图片
       BufferedImage image = QrCodeUtil.generate(content, width, height);
              // 将二维码图片转换成Base64编码的字符串
              ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                 ImgUtil.writePng(image, outputStream);
         return "data:image/png;base64," + Base64.encode(outputStream.toByteArray());    }}*/
}
